package com.nineclock.system.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.filter.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.*;
import com.nineclock.system.mapper.SysCompanyUserMapper;
import com.nineclock.system.mapper.SysDepartmentMapper;
import com.nineclock.system.pojo.SysCompanyUser;
import com.nineclock.system.pojo.SysDepartment;
import com.nineclock.system.service.SysCompanyUserService;
import com.nineclock.system.service.SysDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class SysDepartmentServiceImpl implements SysDepartmentService {

    @Autowired
    private SysDepartmentMapper departmentMapper;

    @Autowired
    private SysCompanyUserMapper companyUserMapper;

    @Autowired
    private SysCompanyUserService companyUserService;

    @Override
    public List<SysDepartmentDTO> queryDepartmentList() {
        // 1). 获取当前登录用户的企业ID
        Long companyId = CurrentUserHolder.get().getCompanyId();

        // 2). 查询当前企业下的顶级部门列表 (parentId为0)
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getCompanyId, companyId);
        wrapper.eq(SysDepartment::getParentId, 0);
        List<SysDepartment> departmentList = departmentMapper.selectList(wrapper);

        if (!CollectionUtils.isEmpty(departmentList)) {

            List<SysDepartmentDTO> departmentDTOList = BeanHelper.copyWithCollection(departmentList, SysDepartmentDTO.class);

            // 3). 递归查询上级部门下的子部门列表数据
            queryChildrenDepartmentList(departmentDTOList);

            // 4). 组装数据并返回
            return departmentDTOList;
        }
        return null;
    }


    /**
     * 递归查询上级部门下的子部门列表数据
     *
     * @param departmentDTOList
     */
    private void queryChildrenDepartmentList(List<SysDepartmentDTO> departmentDTOList) {

        for (SysDepartmentDTO departmentDTO : departmentDTOList) {
            // 查询每个部门下的子部门列表
            LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
            wrapper.eq(SysDepartment::getParentId, departmentDTO.getId());
            List<SysDepartment> childDepartmentList = departmentMapper.selectList(wrapper);

            if (!CollectionUtils.isEmpty(childDepartmentList)) { // 如果子部门不为空，继续查询子部门列表

                List<SysDepartmentDTO> childDepartmentDTOList = BeanHelper.copyWithCollection(childDepartmentList, SysDepartmentDTO.class);

                queryChildrenDepartmentList(childDepartmentDTOList);

                // 设置子部门列表
                departmentDTO.setChildren(childDepartmentDTOList);

            }
        }
    }


    @Override
    public List<Long> queryDepartmentIds() {
        // 获取当前登录用户的企业id
        Long companyId = CurrentUserHolder.get().getCompanyId();

        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getCompanyId, companyId);

        List<SysDepartment> departmentList = departmentMapper.selectList(wrapper);

        if (!CollectionUtils.isEmpty(departmentList)) {

            List<Long> deptIdList = departmentList.stream().map(sysDepartment -> {
                return sysDepartment.getId();
            }).collect(Collectors.toList());

            return deptIdList;
        }
        return null;
    }

    @Override
    public List<DepartmentOrUserSimpleDTO> querySimleDepartment(Long id, Integer includeMember) {

        List<DepartmentOrUserSimpleDTO> resultList = new ArrayList<>();

        // 根据部门id，查询部门下的员工列表
        if (includeMember == 0) {
            LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
            wrapper.eq(SysCompanyUser::getDepartmentId, id);
            wrapper.eq(SysCompanyUser::getEnable, 1);
            List<SysCompanyUser> companyUserList = companyUserMapper.selectList(wrapper);

            if (!CollectionUtils.isEmpty(companyUserList)) {

                for (SysCompanyUser companyUser : companyUserList) {
                    DepartmentOrUserSimpleDTO departmentOrUserSimpleDTO = new DepartmentOrUserSimpleDTO();
                    departmentOrUserSimpleDTO.setId(companyUser.getId()); // 员工id
                    departmentOrUserSimpleDTO.setName(companyUser.getUserName()); // 员工姓名
                    departmentOrUserSimpleDTO.setType(2); // 1-部门，2-员工
                    resultList.add(departmentOrUserSimpleDTO);
                }
            }
        }

        // 根据部门id，查询部门下的子部门列表
        LambdaQueryWrapper<SysDepartment> deptWrapper = new LambdaQueryWrapper<>();
        deptWrapper.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
        deptWrapper.eq(SysDepartment::getParentId, id);
        List<SysDepartment> departmentList = departmentMapper.selectList(deptWrapper);

        if (!CollectionUtils.isEmpty(departmentList)) {

            for (SysDepartment department : departmentList) {
                DepartmentOrUserSimpleDTO departmentOrUserSimpleDTO = new DepartmentOrUserSimpleDTO();
                departmentOrUserSimpleDTO.setId(department.getId()); // 部门id
                departmentOrUserSimpleDTO.setName(department.getName()); // 部门名称
                departmentOrUserSimpleDTO.setType(1); // 1-部门，2-员工
                resultList.add(departmentOrUserSimpleDTO);
            }
        }

        return resultList;
    }

    @Override
    public List<Long> queryDepartmentsByUserId(Long companyUserId) {

        List<Long> deptIdList = new ArrayList<>();

        // 查询员工表，根据员工id查询
        SysCompanyUser companyUser = companyUserMapper.selectById(companyUserId);

        // 递归查询所有的上级部门id集合
        getAllParentDeptIdWithSortById(deptIdList, companyUser.getDepartmentId());

        return deptIdList;
    }




    /**
     * 递归查询所有的上级部门id集合
     * @param deptIdList
     * @param departmentId
     */
    private void getAllParentDeptIdWithSortById(List<Long> deptIdList, Long departmentId) {
        deptIdList.add(departmentId);

        // 根据部门id查询部门信息，得到父级部门id
        SysDepartment department = departmentMapper.selectById(departmentId);

        if (department != null && department.getParentId() != 0) {
            getAllParentDeptIdWithSortById(deptIdList, department.getParentId());
        }

    }

    /**
     * 组织架构:添加部门
     * */
    @Override
    public SysDepartmentDTO addDepartment(SysDepartmentDTO departmentDTO) {
        if (departmentDTO==null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        SysDepartment department=new SysDepartment();
        department.setName(departmentDTO.getName());
        department.setUserId(CurrentUserHolder.get().getId());
        department.setCreateTime(new Date());
        department.setCompanyId(CurrentUserHolder.get().getCompanyId());
        if (departmentDTO.getParent()==null){
            department.setParentId(0L);
        }else {
            department.setParentId(departmentDTO.getParent().getId());
        }
        departmentMapper.insert(department);
        return BeanHelper.copyProperties(department,SysDepartmentDTO.class);
    }

    /**
     * 组织架构:删除部门成员
     * @param ids
     */
    @Override
    public void deleteDepartments(List<Long> ids) {

        if (CollectionUtils.isEmpty(ids)) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }


        for (Long companyUserId : ids) {
            //根据员工id查询所在的部门

            SysCompanyUserDTO sysCompanyUserDTO = companyUserService.queryCompanyUserById(companyUserId);

            if (sysCompanyUserDTO != null) {

                //转移到
                SysCompanyUser companyUser = BeanHelper.copyProperties(sysCompanyUserDTO, SysCompanyUser.class);
                companyUser.setDepartmentId(0L);
                companyUser.setDepartmentName("");

                companyUserMapper.updateById(companyUser);
            }
        }
    }


    @Override
    public List<SysDepartmentDTO> addmember() {
        LambdaQueryWrapper<SysDepartment> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getCompanyId,CurrentUserHolder.get().getCompanyId());
        List<SysDepartment> sysDepartments = departmentMapper.selectList(wrapper);
        return BeanHelper.copyWithCollection(sysDepartments,SysDepartmentDTO.class);
    }

    /**
     * 组织架构:部门调整
     * @param changeDepartmentDTO
     */
    @Override
    public void switchDept(ChangeDepartmentDTO changeDepartmentDTO) {

        SysDepartmentDTO department = changeDepartmentDTO.getDepartment();
        List<SysUserDTO> users = changeDepartmentDTO.getUsers();
        //创建一个空的集合存id
        List<Long> userid = new ArrayList<>();
        for (SysUserDTO user : users) {
            userid.add(user.getId());
        }
        //根据部门id找到部门名称
        SysDepartment sysDepartment = departmentMapper.selectById(department.getId());

        //根据员工id和公司id找到员工的信息
        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUser::getCompanyId,CurrentUserHolder.get().getCompanyId());
        wrapper.in(SysCompanyUser::getId,userid);
        SysCompanyUser sysCompanyUser = companyUserMapper.selectOne(wrapper);

        sysCompanyUser.setDepartmentId(sysDepartment.getId());
        sysCompanyUser.setDepartmentName(sysDepartment.getName());
        companyUserMapper.updateById(sysCompanyUser);

    }

}
